<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <!-- 面包屑路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- /面包屑路径导航 -->
      </div>

      <el-form ref="form" :model="user" label-width="80px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编    号">
              {{ user.id }}
            </el-form-item>
            <el-form-item label="手机号">
              {{ user.mobile }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="用户头像点击修改">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
        >
          <img
            width="100"
            src="http://toutiao-img.itheima.net/Ftb-E6bXjx1HlnJHPhe5N6E_seaI"
            class="avatar"
          />
        </el-upload>
      </el-form-item> -->

            <!-- <p @click="$refs.file.click()" > 点击修改头像</p>-->
            <label for="file">
              <el-avatar
                shape="square"
                :size="150"
                fit="cover"
                :src="user.photo"
              ></el-avatar>
              <p>点击修改头像</p>
            </label>
            <input
              id="file"
              type="file"
              hidden
              ref="file"
              @change="onFileChange"
            />
          </el-col>
        </el-row>

        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item label="个人介绍" prop="intro">
          <el-input type="textarea" v-model="user.intro"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
           type="primary"
           @click="onUpdateInfo">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片对话框 -->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      width="30%"
      @opened="onDialogOpened"
      @closed="closedDialog"
    >
      <div class="imageDiv">
        <img
          class="preview-image"
          :src="previewImage"
          alt=""
          ref="preview-image"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
         @click="onUpdatePhoto"
         :loading="updateLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile , updateUserPhoto , updateUserInfo} from "@/api/user";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import eventBus from "@/utils/global-bus"


  

export default {
  name: "SettingIndex",
  components: {},
  props: {},
  data() {
    return {
      user: {
        email: "",
        id: null,
        intro: "",
        mobile: "",
        name: "",
        photo: "",
      },
      dialogVisible: false,
      previewImage: "", //预览图片
      cropper:null, //裁剪图片的实例
      updateLoading:false,

      //表单验证
       rules: {
          name: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 3, max: 7, message: '长度在 3 到 7 个字符', trigger: 'change' }
          ],
          intro:[
            { required: true, message: '请输入个人介绍', trigger: 'blur' }
            ],
          email:[
             { required: true, message: '请输入邮箱地址', trigger: 'blur' },
           { type: 'email', message: '请输入正确的邮箱地址', trigger:  'change'}
            ],          
        }
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadUser();

  

  },
  methods: {
    onUpdateInfo() {
     //标点验证
     //表单验证通过
      
      //打开loading
         this.updateLoading = true
      const {name , intro , email} = this.user
      updateUserInfo({
        name,
        intro,
        email
      }).then((res) => {
        // console.log(res.data);
        this.updateLoading= false
         this.$message({
          type:"success",
          message:"保存成功"
        })

        //发布 用户修改后的数据
          eventBus.$emit("foo",this.user)
      })
    },
    loadUser() {
      getUserProfile().then((res) => {
        this.user = res.data.data;
       
      });
    },
    onFileChange() {
      const file = this.$refs.file;
      //    console.log(file.files[0]);
      // 通过 file的 file.files[0]拿到图片数据 再使用window 的api
      const imageData = window.URL.createObjectURL(file.files[0]);
      console.log(imageData);
      this.previewImage = imageData;

      //获取文件之后 出现弹出层
      this.dialogVisible = true;

      //解决选择了相同文件不触发change事件的问题
      // console.log(this.$refs.file);
      this.$refs.file.value = "";
    },
    onDialogOpened() {
      //图片裁切器必须基于img进行初始化
      //注意：img必须在可见状态下才能初始化 在弹出层完全打开的时候就可以进行初始化了
      
      //vue 获取DOM节点
      const image = this.$refs["preview-image"];
      this.cropper = new Cropper(image, {
        aspectRatio: 16 / 9,
      });
    },
    closedDialog() {
      // this.cropper = null //错误方法 没用
      this.cropper.destroy()
    },
    onUpdatePhoto(){
      //获取裁切的图片对象
      
       this.cropper.getCroppedCanvas().toBlob((blob) => {
            const fd = new FormData()
            fd.append('photo',file)
            //请求提交fd
            updateUserPhoto(fd).then((res) => {
              // console.log(res);
              this.dialogVisible = false
              //更行视图
              //后端的这个接口不再返回 photo的数据了
              // this.user.photo = res.data.data.photo
             
             //快速预览     不经过后端
             this.user.photo=window.URL.createObjectURL(blob)
          
          
            })
       })
       //请求更行用户头像
      //关闭对话框
      //更新视图展示
    }
  },
};
</script>

<style scoped lang="less">
.imageDiv {
  .preview-image {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
    height: 220px;
  }
}
</style>